<!-- 用户管理 -->
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import * as userApi from '@/api/user'
import * as orgApi from '@/api/org'
import type { IDbAction, IDbSearchConfig, IDbTable, ITagData } from '@/types/global'
import useNotic from '@/hooks/useNotic'
import UserInfo from './comps/UserInfo.vue'
import UserAllot from './comps/UserAllot.vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { ENUM_BTN_AUTH_SYS } from '@/config/btn'
import { USER_DISABLE_LIST } from './config'

const treeData = reactive({
  list: [] as any[],
  props: { label: 'orgName', isLeaf: 'isLeaf', children: 'children' },
  keyword: ''
})
// 搜索栏配置
const searchConfig = reactive<IDbSearchConfig[]>([
  { label: '用户名称', prop: 'userName', type: 'input' },
  { label: '手机号码', prop: 'phonenumber', type: 'input' }
])

// 表格数据
const tableData = reactive<IDbTable>({
  columns: [
    { label: '序号', prop: '', type: 'index', width: '60px' },
    { label: '用户编号', prop: 'userId', width: '160px' },
    { label: '用户名称', prop: 'userName', minWidth: '100px' },
    { label: '用户昵称', prop: 'nickName', minWidth: '100px' },
    { label: '手机号', prop: 'phonenumber', minWidth: '100px' },
    {
      label: '状态',
      prop: 'status',
      width: '100px',
      type: 'tag',
      tagFunc: (scope) => {
        const curStatus = USER_DISABLE_LIST.find((item) => item.value == scope.row.status)
        const tagData: ITagData = { label: curStatus?.label || '', type: curStatus?.tagType || '' }
        return tagData
      }
    },
    { label: '创建时间', prop: 'createTime', width: '200px' },
    { label: '操作', prop: 'handle', fixed: 'right', type: 'slot', width: '150px' }
  ],
  data: [],
  total: 0,
  search: {
    pageNum: 1,
    pageSize: 20,
    userName: '',
    phonenumber: '',
    orgId: ''
  }
})

// 弹窗数据
const userInfoRef = ref<InstanceType<typeof UserInfo>>()
const userRoleRef = ref<InstanceType<typeof UserAllot>>()
const dialogData = reactive({
  title: '', // 用户信息弹窗标题
  disabled: false, // 是否禁用用户信息弹窗
  titleRole: '' // 分配角色标题
})

getDataList()

/**
 * 点击添加
 */
function addClick() {
  dialogData.title = '添加用户'
  dialogData.disabled = false
  userInfoRef.value?.init()
}
/**
 * 点击详情/编辑
 */
function infoClick(row: any, disabled: boolean) {
  dialogData.title = disabled ? '用户详情' : '编辑用户'
  dialogData.disabled = disabled
  userInfoRef.value?.init(row.userId)
}
/**
 * 点击删除
 */
function delClick(scoped: any) {
  useNotic().confirm(`您确定要删除第${scoped.$index + 1}个用户吗？`, (flag) => {
    if (flag) {
      userApi.delUser(scoped.row.userId).then((res) => {
        if (res.success) {
          useNotic().success('删除成功')
          getDataList()
        }
      })
    }
  })
}
/**
 * 点击分配角色
 */
function allotClick(row: any) {
  dialogData.titleRole = `${row.userName}-分配角色`
  userRoleRef.value?.init(row.userId)
}
/**
 * 设置按钮列表
 */
function setBtnList(scoped: any) {
  const list: IDbAction[] = [
    { label: '详情', type: 'primary', auth: ENUM_BTN_AUTH_SYS['用户:查'], onClick: () => infoClick(scoped.row, true) },
    { label: '编辑', type: 'primary', auth: ENUM_BTN_AUTH_SYS['用户:改'], onClick: () => infoClick(scoped.row, false) },
    { label: '删除', type: 'danger', auth: ENUM_BTN_AUTH_SYS['用户:删'], onClick: () => delClick(scoped) },
    { label: '分配角色', type: 'primary', auth: ENUM_BTN_AUTH_SYS['用户:分配角色'], onClick: () => allotClick(scoped.row) }
  ]
  return list
}
/**
 * 点击树节点事件
 */
function nodeClick(curNode: any) {
  if (curNode) {
    tableData.search!.orgId = curNode.id
  } else {
    tableData.search!.orgId = ''
  }
  getDataList()
}
/**
 * 获取表格数据
 */
function getDataList() {
  userApi.getUserList(tableData.search).then((res) => {
    if (res.success) {
      tableData.data = res.data.rows
      tableData.total = res.data.total
    }
  })
}
/**
 * 树节点加载事件
 */
function treeLoadEvt(node: Node) {
  let params = {}
  // 根节点加载
  if (node.level === 0) {
    params = { initOrg: 1 }
  }
  // 子节点加载
  else {
    params = { parentId: node.data.id }
  }

  return new Promise((resolve) => {
    orgApi.getChildrenByOrgId(params).then((res) => {
      if (res.success) {
        const normalList = res.data.rows
        resolve(normalList)
      }
    })
  })
}
</script>

<template>
  <dui-page :search-config="searchConfig" :search-data="tableData.search" @search="getDataList">
    <template #tree>
      <dui-lazy-tree :load="treeLoadEvt" :props="treeData.props" @node-click="nodeClick" />
    </template>
    <template #btn>
      <db-auth-btn :auth="ENUM_BTN_AUTH_SYS['用户:增']" type="primary" iconType="add" @click="addClick"> 添加用户 </db-auth-btn>
    </template>
    <template #default>
      <dui-table
        :data="tableData.data"
        :columns="tableData.columns"
        :total="tableData.total"
        :search="tableData.search"
        @search="getDataList"
      >
        <template #handleSlot="scoped">
          <dui-action :list="setBtnList(scoped)" />
        </template>
      </dui-table>
      <!-- 用户信息弹窗 -->
      <UserInfo ref="userInfoRef" :title="dialogData.title" :disabled="dialogData.disabled" @refresh="getDataList" />
      <!-- 分配角色弹窗 -->
      <UserAllot ref="userRoleRef" :title="dialogData.titleRole" />
    </template>
  </dui-page>
</template>
